use rbatis::crud::{Skip, CRUD};
use rbatis::rbatis::Rbatis;
use bson2::Bson;

use chrono::prelude::*;

use crate::dbs::sqlite::Peer;
use crate::features::events::modelsdbo::Event;
use crate::features::events::modelsdbo::EventDBO;

/// append event to event-store
pub async fn append(
  rbatis_pool: &Rbatis,
  my_peer: &Peer,
  source_id: &str,
  event: &Event,
) -> Result<rbatis::db::DBExecResult, rbatis::Error> {
  let now: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z`

  let event_dbo = EventDBO {
    id: my_peer.timestamp(),
    source: source_id.to_owned(),
    data: event.to_owned(),
    user_id: my_peer.login_user_id.to_owned(),
    created_at: now.timestamp(),
  };

  let db_result = rbatis_pool
    .save::<EventDBO>(&event_dbo, &[Skip::Value(Bson::Null)])
    .await;

  println!("events::services::append() db_result={:?}", db_result);
  db_result
}
